import 'dart:convert';
import 'package:fenzi/iconfont.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';
import 'package:fenzi/components/toast.dart';
import 'package:fenzi/common/utils.dart';
import 'package:fenzi/global.dart';
import 'package:fenzi/components/form_text.dart';
import 'package:fenzi/components/item.dart';
import 'package:fenzi/components/text_item.dart';
import 'package:fenzi/manager/main_manager.dart';
import 'package:provider/provider.dart';

class EditPage extends StatefulWidget {
  EditPage({Key key, this.id, this.data}) : super(key: key);
  final data;
  final id;

  @override
  State<StatefulWidget> createState() => _EditPageState();
}

class _EditPageState extends State<EditPage> {
  var _data = {
    'spending': true,
    'date': '2020-09-01',
    'name': '张三',
    'relation': '',
    'co': '100',
    'type': 'other',
    'remark': '张三第三次结婚，送上自己最真挚的祝福！',
  };
  @override
  void initState() {
    setState(() {
      _data = widget.data;
    });
    super.initState();
  }

  String getTypeName(type) {
    String zhName;
    switch (type) {
      case 'male':
        zhName = '男方';
        break;
      case 'famale':
        zhName = '女方';
        break;
      case 'child':
        zhName = '孩子';
        break;
      case 'friend':
        zhName = '朋友';
        break;
      case 'other':
        zhName = '其他';
        break;
      default:
        zhName = '其他';
    }
    return zhName;
  }

  getTypes() {
    List<Widget> list = [];
    List<String> items = [
      'male',
      'famale',
      'child',
      'friend',
      'other',
    ];

    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      bool checked = item == _data['type'];
      list.add(
        InkWell(
          onTap: () {
            setState(() {
              _data['type'] = item;
            });
            Navigator.pop(context);
          },
          child: Container(
            width: MediaQuery.of(context).size.width / 7,
            padding: EdgeInsets.fromLTRB(6, 2, 6, 2),
            margin: EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: checked ? Global.primaryColor : Global.backgroundColor,
              border: Border.all(
                  color: checked ? Global.backgroundColor : Global.primaryColor,
                  width: 1),
              borderRadius: BorderRadius.circular(40),
            ),
            child: Center(
              child: Text(
                getTypeName(item),
                style: TextStyle(
                  color: checked ? Global.backgroundColor : Global.primaryColor,
                  fontSize: 14,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ),
        ),
      );
    }
    return list;
  }

  Future _openModalBottomSheet() async {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          padding: EdgeInsets.all(10),
          height: 180,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Wrap(
                children: getTypes(),
              ),
            ],
          ),
        );
      },
    );
  }

  Future _openSpendingModalBottomSheet() async {
    await showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: 130,
          child: Column(
            children: <Widget>[
              ListTile(
                title: Text(
                  '收入',
                  style: TextStyle(color: Color(0xFF14b1ab)),
                  textAlign: TextAlign.center,
                ),
                onTap: () {
                  setState(() {
                    _data['spending'] = false;
                  });
                  Navigator.pop(context);
                },
              ),
              ListTile(
                title: Text('支出',
                    style: TextStyle(color: Color(0xFFe84a5f)),
                    textAlign: TextAlign.center),
                onTap: () {
                  setState(() {
                    _data['spending'] = true;
                  });
                  Navigator.pop(context);
                },
              ),
            ],
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    MainManager _mainManager = Provider.of<MainManager>(context);

    return Scaffold(
      appBar: AppBar(
        iconTheme: IconThemeData(color: Global.backgroundColor),
        toolbarHeight: 50,
        elevation: 0,
        title: Text(
          "${widget.id == '000' ? '添加' : '编辑'}账簿",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: Global.backgroundColor,
            fontSize: 15,
          ),
        ),
        actions: <Widget>[
          Offstage(
            offstage: widget.id == '000', //这里控制
            child: IconButton(
              icon: Icon(Icons.delete),
              tooltip: '删除',
              onPressed: () {
                Utils.showConfirmDialog(
                  context: context,
                  content: '确认删除该项？',
                  confirmCallback: () {
                    _mainManager.delete(widget.id.toString());
                    Navigator.pop(context);
                  },
                  showCancelButton: true,
                );
              },
            ),
          ),
          IconButton(
            icon: Icon(IconFont.wanchengchenggong),
            tooltip: '保存',
            onPressed: () {
              if (_data['name'].toString().trim() == '') {
                Toast.show(context, msg: '您还没有填写对方姓名');
                return;
              }
              if (_data['co'].toString().trim() == '') {
                Toast.show(context, msg: '您还没有填写来往金额');
                return;
              }
              if (_data['relation'].toString().trim() == '') {
                Toast.show(context, msg: '您还没有填写与对方的关系');
                return;
              }
              if (_data['remark'].toString().length > 50) {
                Toast.show(context, msg: '请修改备注为50字以内');
                return;
              }
              if (widget.id == '000') {
                String id = DateTime.now().millisecondsSinceEpoch.toString();
                _mainManager.insert(id, json.encode(_data));
              } else {
                _mainManager.update(widget.id.toString(), json.encode(_data));
              }
              Navigator.pop(context);
            },
          ),
        ],
      ),
      body: Container(
        width: MediaQuery.of(context).size.width,
        height: MediaQuery.of(context).size.height,
        decoration: BoxDecoration(color: Global.cardBackgroundColor),
        child: SingleChildScrollView(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Item(
                title: "收支",
                hintText: "请选择类型",
                text: _data['spending'] ? "支出" : "收入",
                onTap: () {
                  _openSpendingModalBottomSheet();
                },
              ),
              Item(
                title: "日期",
                text: _data['date'],
                hintText: "请选择日期",
                onTap: () {
                  DatePicker.showDatePicker(
                    context,
                    pickerTheme: DateTimePickerTheme(confirm: Text('确定')),
                    onMonthChangeStartWithFirstDate: true,
                    minDateTime: DateTime.parse('2020-09-20'),
                    maxDateTime: DateTime.parse('2022-12-31'),
                    initialDateTime: DateTime.now(),
                    dateFormat: 'yyyy-MMMM-dd',
                    locale: DateTimePickerLocale.zh_cn,
                    onConfirm: (dateTime, List<int> index) {
                      setState(() {
                        _data['date'] = dateTime.toString().substring(0, 10);
                      });
                    },
                  );
                },
              ),
              SizedBox(height: 10),
              TextItem(
                title: "姓名",
                text: _data['name'],
                hintText: "输入对方姓名",
                onChanged: (text) {
                  setState(() {
                    _data['name'] = text;
                  });
                },
              ),
              Item(
                title: "类型",
                text: getTypeName(_data['type']),
                hintText: "选择对方类型",
                onTap: () {
                  _openModalBottomSheet();
                },
              ),
              TextItem(
                title: "关系",
                text: _data['relation'],
                hintText: "输入与对方关系",
                onChanged: (text) {
                  setState(() {
                    _data['relation'] = text;
                  });
                },
              ),
              SizedBox(height: 10),
              TextItem(
                title: "礼金",
                text: _data['co'],
                hintText: "输入礼金",
                keyboardType: TextInputType.number,
                onChanged: (text) {
                  setState(() {
                    _data['co'] = text;
                  });
                },
              ),
              SizedBox(height: 10),
              Container(
                padding: EdgeInsets.all(10),
                width: MediaQuery.of(context).size.width,
                decoration: BoxDecoration(
                  color: Global.backgroundColor,
                  border: Border(
                    bottom: BorderSide(
                      color: Global.fontSecondColor.withOpacity(0.2),
                      width: 1,
                      style: BorderStyle.solid,
                    ),
                  ),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Text(
                      "备注",
                      style: TextStyle(
                        fontSize: 16,
                        color: Global.fontColor,
                      ),
                    ),
                    SizedBox(height: 5),
                    FormText(
                      maxLine: 4,
                      text: _data['remark'],
                      hintText: "最多50个字（选填）",
                      textAlign: TextAlign.start,
                      onChanged: (text) {
                        setState(() {
                          _data['remark'] = text;
                        });
                      },
                    ),
                  ],
                ),
              )
            ],
          ),
        ),
      ),
    );
  }
}
